import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by HP on 2018/10/2.
 */
public class Servletdemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      /*  String name = request.getParameter("name");
        String password = request.getParameter("password");
        //请求转发需要重新给request进行赋值,不然在jsp中取不到相同属性名称的值
        request.setAttribute("name",name);
        request.setAttribute("password",password);
        System.out.println(name+"-----"+password);
        User user=new User(name,25,password);
        List<User> userList=new ArrayList<>();
        userList.add(user);
        userList.add(user);
        request.setAttribute("userlist",userList);
        request.setAttribute("users",user);
        //后端往前端发送json
        ObjectMapper objectMapper=new ObjectMapper();
        String s = objectMapper.writeValueAsString(user);
        request.setAttribute("user",s);*/
      //后端对前端的json进行接收并显示,也可以接收前端提交的表单的信息,但是会发生乱码的情况
        //ajax的使用不会造成页面的刷新或者跳转,因此,ajax主要用于对局部信息的修改
      StringBuffer stringBuffer=new StringBuffer();
        BufferedReader reader = request.getReader();
        String s=null;
        while ((s=reader.readLine())!=null){
            stringBuffer.append(s);
        }
        System.out.println(stringBuffer.toString());

       response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(stringBuffer.toString());
//        request.getRequestDispatcher("/WEB-INF/demo.jsp").forward(request,response);
        //servlet请求转发的时候,不需要写斜杠线表示转发路径
       /* request.setAttribute("type","POST");
        response.sendRedirect("demo2");*/
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        response.getWriter().write(name);
        System.out.println(name+"-----"+password);
    }
}
